package com.server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

public class TankServer {

	public static final int TcpPort = 8888;
	
	public static final int UdpPort = 6666;

	List<Client> clients = new ArrayList<Client>();
	
	private static  int netId = 100;

	public void start() {

		new Thread(new UpdThread()).start();
		
		ServerSocket ss = null;
		try {
			ss = new ServerSocket(TcpPort);
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		while (true) {
			Socket socket = null;
			try {
				socket = ss.accept();
				System.out.print("Addr:" + ss.getInetAddress() + ",port:" + ss.getLocalPort() + "\n");
				DataInputStream dis = new DataInputStream(socket.getInputStream());
				String ip = socket.getInetAddress().getHostAddress();
				int udpPort = dis.readInt();
				Client client = new Client(ip, udpPort);
				clients.add(client);
				DataOutputStream dos  = new DataOutputStream(socket.getOutputStream());
				dos.writeInt(netId++);
				System.out.print("Accect " + ip + " udpPort is:" + udpPort);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (socket != null) {
					try {
						socket.close();
						socket = null;
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}

		}
	}

	public static void main(String[] args) {
		new TankServer().start();
	}

	private class Client {

		public String ip;

		public int udp_Port;

		public Client() {

		}

		public Client(String ip, int udp_port) {
			this.ip = ip;
			this.udp_Port = udp_port;
		}
	}
	
	private class UpdThread implements Runnable{

		byte []  buf = new byte[1024];
		@Override
		public void run() {
			
			DatagramSocket  ds = null;
			
			System.out.println("UdpThread Started at port:"+UdpPort);
			
			try {
				ds = new DatagramSocket(UdpPort);
			} catch (SocketException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			while(ds!=null){
				DatagramPacket dp  = new DatagramPacket(buf,buf.length);
				try {
					ds.receive(dp);
					System.out.println("a packet receive!");
					
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		}
		
	}

}
